package com.tiennt.android.callnotes.utils;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.util.Log;

import com.tiennt.android.callnotes.R;
import com.tiennt.android.callnotes.models.contentholders.ContactInfo;

public class ContactUtils {
	public static String TAG = "ContactUtils";
	public static boolean DBG = true;

	public static void log(String msg) {
		if (DBG) {
			Log.d(TAG, msg);
		}
	}

	public static ContactInfo getContactInfo(Context context, long contactId) {
		Bitmap photoBitmap = BitmapFactory.decodeResource(
				context.getResources(), R.drawable.contact_image);
		ContactInfo contactInfo = null;
		Uri contactUri = ContentUris.withAppendedId(
				ContactsContract.Contacts.CONTENT_URI, contactId);

		Cursor cursor = context.getContentResolver().query(contactUri, null,
				null, null, null);
		if (cursor.moveToFirst()) {
			contactInfo = new ContactInfo();
			contactInfo.setContactId(contactId);
			contactInfo.setContactName(cursor.getString(cursor
					.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));

			String photoWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
					+ ContactsContract.Data.MIMETYPE + " = ?";
			String[] photoWhereParams = new String[] {
					String.valueOf(contactId),
					ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE };
			Cursor photoCur = context.getContentResolver().query(
					ContactsContract.Data.CONTENT_URI, null, photoWhere,
					photoWhereParams, null);
			photoCur.moveToFirst();
			if (photoCur.moveToFirst() && photoCur != null) {

				byte[] photoBlob = photoCur.getBlob(photoCur
						.getColumnIndex(Photo.PHOTO));
				if (photoBlob != null) {
					photoBitmap = BitmapFactory.decodeByteArray(photoBlob, 0,
							photoBlob.length);

				}
			}
			photoCur.close();
		}
		
		
		if (photoBitmap != null){
			contactInfo.setContactPhoto(photoBitmap);
		}
		
		cursor.close();
		return contactInfo;
	}

	public static ContactInfo getContactFromSIM(Context context, String phoneNum) {
		Uri simUri = Uri.parse("content://icc/adn");
		ContactInfo info = new ContactInfo();
		Cursor cursorSim = context.getContentResolver().query(simUri, null,
				"number = '" + phoneNum + "'", null, null);

		if (cursorSim.moveToFirst()) {
			info.setContactId(Long.parseLong(cursorSim.getString(cursorSim
					.getColumnIndex("_id"))));
			info.setContactName(cursorSim.getString(cursorSim
					.getColumnIndex("name")));
		}
		return info;
	}
}
